package fr.emn.fil.soc.gr3.restws;

import java.util.List;
import java.util.UUID;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fr.emn.fil.soc.gr3.entites.Compte;

public class TokenUtil {

	public static String generateToken() {
		return ""+UUID.randomUUID();
	}
	
	
	@SuppressWarnings("unchecked")
	public static boolean tokenExists(String token) {
		boolean result = false;
		DBConnection dbConnection = new DBConnection();
		EntityManager em = dbConnection.createConnection();

		Query query = em.createQuery("SELECT c FROM " + Compte.class.getName() + " c WHERE c.token=:token");
		query.setParameter("token", token);

		try {
			List<Compte> matchingComptes = (List<Compte>) query.getResultList();
			if(matchingComptes != null && matchingComptes.size() == 1) {
				result = true;
			}
		} catch (Exception e) {
			result = false;
		}

		dbConnection.closeConnection();
		return result;
	}
}
